package tcp;

import com.nativetalk.base.Params;
import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.teacher.TdNtTeacherResult;
import com.nativetalk.common.SpringConfig;
import com.nativetalk.common.util.BeanToJson;
import com.nativetalk.common.util.CommonUtil;
import com.nativetalk.common.util.JsonToBean;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.service.live.LiveService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by lizhun
 * Modified by wangzheng on 17/02/25
 */
public class ClientTask {
    private static final Logger logger = Logger.getLogger(ClientTask.class.getName());
    private static Long markId = 0L;
    private long id = 0;
    @Autowired
    @Qualifier("liveService")
    private static LiveService liveService;

    static {

        AbstractApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        liveService = (LiveService) ctx.getBean("liveService");
    }

    private Channel channel;

    public ClientTask(Channel channel) {
        synchronized (markId) {
            this.id = ++markId;
        }
        this.channel = channel;
    }

    public void acceptRequest(final String params, ConcurrentHashMap<String, Channel> cilentChannelMap) {
        try {
            logger.info("--------------- tcp request from " + channel == null ? "null" : channel.toString() + " params  ---->>> \n" + params + "\n------------------ end -------------------");
            Params paramsBean = JsonToBean.JsonToParams(params);
            cilentChannelMap.put(paramsBean.getMustParams().get("token") + "client", channel);
            /**
             * 判断版本号,用户时间戳及加密信息
             */
            switch (paramsBean.getFunctionName()) {
                /**
                 * 点亮
                 */
                case "Light": {
                    RetInfo retInfo = liveService.light(paramsBean);
//					cilentChannelMap.get(paramsBean.getMustParams().get("token")+"client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                    if (retInfo.getMark().equals("0")) {
                        int live_cou_his_id = Integer.valueOf(paramsBean.getParams().get("live_cou_his_id").toString());
                        List<TdNtMember> tdNtMembers = liveService.findTdNtMemberByLive(live_cou_his_id);
                        for (int i = 0; i < tdNtMembers.size(); i++) {
                            if (cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client") != null) {
                                cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                            }

                        }
                        TdNtTeacherResult tdNtTeacherResult = liveService.findTdNtTeacher(live_cou_his_id);
                        cilentChannelMap.get(tdNtTeacherResult.getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                    }
                    break;
                }
                /**
                 * 送礼
                 */
                case "Gifts": {
                    RetInfo retInfo = liveService.give(paramsBean);
//					cilentChannelMap.get(paramsBean.getMustParams().get("token")+"client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                    /**
                     *
                     */
                    if (retInfo.getMark().equals("0")) {
                        int live_cou_his_id = Integer.valueOf(paramsBean.getParams().get("live_cou_his_id").toString());
                        List<TdNtMember> tdNtMembers = liveService.findTdNtMemberByLive(live_cou_his_id);
                        for (int i = 0; i < tdNtMembers.size(); i++) {
                            if (cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client") != null) {
                                cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                            }

                        }
                        TdNtTeacherResult tdNtTeacherResult = liveService.findTdNtTeacher(live_cou_his_id);
                        cilentChannelMap.get(tdNtTeacherResult.getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                    }
                    break;
                }
                /**
                 *
                 * 老师注册
                 */
                case "teacher": {
//					RetInfo retInfo = new RetInfo();
//					retInfo.setMark("0");
//					retInfo.setTip("链接成功");
//					cilentChannelMap.get(paramsBean.getMustParams().get("token")+"client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));

                    break;
                }
                /**
                 *
                 * 学生注册注册
                 */
                case "student": {
//					RetInfo retInfo = new RetInfo();
//					retInfo.setMark("0");
//					retInfo.setTip("链接成功");
//					cilentChannelMap.get(paramsBean.getMustParams().get("token")+"client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));

                    break;
                }
                /**
                 *
                 * 指定课程随机呼叫老师
                 */
                case "randomKallTeacer": {
                    RetInfo retInfo = liveService.randomKallTeacer(paramsBean, cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(retInfo);
                    cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));

                    break;
                }
                /**
                 *
                 * 呼叫老师自由话题
                 */
                case "kallTeacerFreeCourse": {
                    RetInfo retInfo = liveService.kallTeacerFreeCourse(paramsBean, cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(retInfo);
                    cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));

                    break;
                }
                /**
                 *
                 * 指定课程指定老师
                 */
                case "kallTeacer": {
                    RetInfo retInfo = liveService.kallTeacer(paramsBean, cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(retInfo);
                    cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));

                    break;
                }
                /**
                 *
                 * 接单
                 */
                case "eceivingOrders": {
                    RetInfo retInfo = liveService.eceivingOrders(paramsBean);
                    logger.info(cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(retInfo);
                    cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo)).addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (!future.isSuccess()) {
                                logger.info("传输文件不成功");
                                logger.info("失败原因为 {}", future.cause());
                            }
                        }
                    });

                    break;
                }
                /**
                 *
                 * 取消
                 */
                case "cancelOrders": {
                    RetInfo retInfo = liveService.eceivingOrders(paramsBean);
                    logger.info(cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));

                    break;
                }
                /**
                 *
                 * 结束课程
                 */
                case "endOrders": {
                    RetInfo retInfo = liveService.endOrders(paramsBean);
                    logger.info(cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(retInfo);
                    cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));

                    break;
                }
                /**
                 *
                 * 翻页
                 */
                case "flip": {
                    RetInfo retInfo = new RetInfo();
                    retInfo.setMark("0");
                    retInfo.setTip("翻页");
                    Map<String, Object> map = paramsBean.getParams();
                    map.put("type", "flip");
                    retInfo.setObj(map);
                    //校验参数
                    Object pageObj = map.get("page");
                    if (pageObj == null) {
                        retInfo.setMark("1");
                        retInfo.setTip("传的参数page为null");
                        channel.writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                        return;
                    } else {
                        if (!CommonUtil.isNumeric(pageObj.toString())) {
                            retInfo.setMark("1");
                            retInfo.setTip("传的参数page不为数字");
                            channel.writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                            return;
                        }
                    }

                    /**
                     * 在缓存里写入当前的页数，使得下次通话进入课程后停留在上次翻到的页码上
                     */
                    String stt_id = map.get("stt_id").toString();
                    if (MemcachedUtils.get(stt_id + "stt_id") != null) {
                        MemcachedUtils.replace(stt_id + "stt_id", map.get("page"), 20 * 60 * 60 * 1000);
                    } else {
                        MemcachedUtils.add(stt_id + "stt_id", map.get("page"), 20 * 60 * 60 * 1000);
                    }

                    TdNtMember member = liveService.findTdNtMemberBySttId(paramsBean);
                    Channel channel = cilentChannelMap.get(member.getToken() + "client");
                    logger.info("发送翻页数据，使用channel：" + channel.toString());
                    channel.writeAndFlush(BeanToJson.RetInfoToJson(retInfo)).addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (future.isSuccess()) {
                                logger.info("翻页发送成功");

                            } else {
                                logger.error("翻页发送失败,原因为:", future.cause());
                            }
                            if (future.isDone()) {
                                logger.info("翻页传送完成");
                            }
                        }
                    });

                    break;
                }
                /**
                 *
                 * 学生预约呼叫
                 */
                case "reserveStudentKall": {
                    RetInfo retInfo = liveService.reserveStudentKall(paramsBean, cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(retInfo);
                    cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));

                    break;
                }
                /**
                 *
                 *  老师拒绝
                 */
                case "teacherRefuse": {
                    RetInfo retInfo = liveService.teacherRefuse(paramsBean, cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(retInfo);
                    cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));

                    break;
                }
                /**
                 *
                 * 老师预约呼叫
                 */
                case "reserveTeacherKall": {
                    RetInfo retInfo = liveService.reserveTeacherKall(paramsBean, cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(retInfo);
                    cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));

                    if ("取消成功".equals(retInfo.getTip())) {
                        TdNtMember tdNtMember = liveService.findTdMembByReserveId(Integer.valueOf(paramsBean.getParams().get("reserve_id").toString()));
                        if (cilentChannelMap.get(tdNtMember.getToken() + "client") != null) {
                            cilentChannelMap.get(tdNtMember.getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                        }
                    }

                    break;
                }
                /**
                 *
                 *  学生拒绝
                 */
                case "studentRefuse": {
                    RetInfo retInfo = liveService.studentRefuse(paramsBean, cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(retInfo);
                    cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));

                    break;
                }
                /**
                 *
                 * 学生接单(学生接听老师的呼叫电话)
                 */
                case "eceivingStudentOrders": {
                    RetInfo retInfo = liveService.eceivingStudentOrders(paramsBean);
                    logger.info(cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(retInfo);
                    cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo)).addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (!future.isSuccess()) {
                                logger.info("传输文件不成功");
                                logger.info("失败原因为 {}", future.cause());
                            }
                        }
                    });

                    break;
                }
                /**
                 * 送礼
                 */
                case "givePurchase": {
                    RetInfo retInfo = liveService.givePurchase(paramsBean);
                    /**
                     *
                     */
                    if (retInfo.getMark().equals("0")) {
                        int live_cou_his_id = Integer.valueOf(paramsBean.getParams().get("live_cou_his_id").toString());
                        List<TdNtMember> tdNtMembers = liveService.findTdNtMemberByLive(live_cou_his_id);
                        for (int i = 0; i < tdNtMembers.size(); i++) {
                            if (cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client") != null) {
                                cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                            }

                        }
                        TdNtTeacherResult tdNtTeacherResult = liveService.findTdNtTeacher(live_cou_his_id);
                        cilentChannelMap.get(tdNtTeacherResult.getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                    }
                    break;
                }
                /**
                 *
                 * 指定课程指定老师
                 */
                case "randomFreeKallTeacer": {
                    RetInfo retInfo = liveService.randomFreeKallTeacer(paramsBean, cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client"));
                    logger.info(retInfo);
                    cilentChannelMap.get(paramsBean.getMustParams().get("token") + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));

                    break;
                }

                /**
                 * 学生加入聊天
                 */
                case "joinChat": {
                    RetInfo retInfo = liveService.joinChat();
                    TdNtMember member = liveService.findTdNtMemberBySttId(paramsBean);
                    cilentChannelMap.get(member.getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));

                    break;
                }

                /**
                 * 学生退出聊天
                 */
                case "exitChat": {
                    RetInfo retInfo = liveService.exitChat();
                    TdNtMember member = liveService.findTdNtMemberBySttId(paramsBean);
                    cilentChannelMap.get(member.getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));

                    break;
                }

                /**
                 * 学生直播课举手
                 */
                case "studentHandsUp": {
                    RetInfo retInfo = liveService.handsUp(paramsBean);
                    if (retInfo.getMark().equals("0")) {
                        int live_cou_his_id = Integer.valueOf(paramsBean.getParams().get("live_cou_his_id").toString());
                        List<TdNtMember> tdNtMembers = liveService.findTdNtMemberByLive(live_cou_his_id);
                        for (int i = 0; i < tdNtMembers.size(); i++) {
                            if (cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client") != null) {
                                cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                            }

                        }
                        TdNtTeacherResult tdNtTeacherResult = liveService.findTdNtTeacher(live_cou_his_id);
                        cilentChannelMap.get(tdNtTeacherResult.getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                    }

                    break;
                }

                /**
                 * 学生直播课放弃举手
                 */
                case "studentHandsDown": {
                    RetInfo retInfo = liveService.handsDown(paramsBean);
                    if (retInfo.getMark().equals("0")) {
                        int live_cou_his_id = Integer.valueOf(paramsBean.getParams().get("live_cou_his_id").toString());
                        List<TdNtMember> tdNtMembers = liveService.findTdNtMemberByLive(live_cou_his_id);
                        for (int i = 0; i < tdNtMembers.size(); i++) {
                            if (cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client") != null) {
                                cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                            }

                        }
                        TdNtTeacherResult tdNtTeacherResult = liveService.findTdNtTeacher(live_cou_his_id);
                        cilentChannelMap.get(tdNtTeacherResult.getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                    }

                    break;
                }

                /**
                 * 老师让学生上麦
                 */
                case "letStudentTalk": {
                    RetInfo retInfo = liveService.letMembTalk(paramsBean);
                    if (retInfo.getMark().equals("0")) {
                        int live_cou_his_id = Integer.valueOf(paramsBean.getParams().get("live_cou_his_id").toString());
                        List<TdNtMember> tdNtMembers = liveService.findTdNtMemberByLive(live_cou_his_id);
                        for (int i = 0; i < tdNtMembers.size(); i++) {
                            if (cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client") != null) {
                                cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                            }

                        }
                        TdNtTeacherResult tdNtTeacherResult = liveService.findTdNtTeacher(live_cou_his_id);
                        cilentChannelMap.get(tdNtTeacherResult.getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                    }

                    break;
                }

                /**
                 * 老师让学生下麦
                 */
                case "letStudentStopTalk": {
                    RetInfo retInfo = liveService.letMembStopTalk(paramsBean);
                    if (retInfo.getMark().equals("0")) {
                        int live_cou_his_id = Integer.valueOf(paramsBean.getParams().get("live_cou_his_id").toString());
                        List<TdNtMember> tdNtMembers = liveService.findTdNtMemberByLive(live_cou_his_id);
                        for (int i = 0; i < tdNtMembers.size(); i++) {
                            if (cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client") != null) {
                                cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                            }

                        }
                        TdNtTeacherResult tdNtTeacherResult = liveService.findTdNtTeacher(live_cou_his_id);
                        cilentChannelMap.get(tdNtTeacherResult.getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                    }

                    break;
                }

                /**
                 * 学生直播课下麦
                 */
                case "studentStopTalk": {
                    RetInfo retInfo = liveService.membStopTalk(paramsBean);
                    if (retInfo.getMark().equals("0")) {
                        int live_cou_his_id = Integer.valueOf(paramsBean.getParams().get("live_cou_his_id").toString());
                        List<TdNtMember> tdNtMembers = liveService.findTdNtMemberByLive(live_cou_his_id);
                        for (int i = 0; i < tdNtMembers.size(); i++) {
                            if (cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client") != null) {
                                cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                            }

                        }
                        TdNtTeacherResult tdNtTeacherResult = liveService.findTdNtTeacher(live_cou_his_id);
                        cilentChannelMap.get(tdNtTeacherResult.getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                    }

                    break;
                }

                /**
                 *  直播课翻页
                 */
                case "liveFlip": {
                    RetInfo retInfo = new RetInfo();
                    retInfo.setMark("0");
                    retInfo.setTip("翻页");
                    Map<String, Object> map = paramsBean.getParams();
                    map.put("type", "liveFlip");
                    retInfo.setObj(map);
                    int live_cou_his_id1 = Integer.valueOf(map.get("live_cou_his_id").toString());
                    List<TdNtMember> tdNtMembers = liveService.findTdNtMemberByLive(live_cou_his_id1);
                    for (int i = 0; i < tdNtMembers.size(); i++) {
                        if (cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client") != null) {
                            cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                        }

                    }

                    break;
                }

                /**
                 * 直播课学生开启或关闭摄像头
                 */
                case "studentOpenOrCloseCamera": {
                    RetInfo retInfo = liveService.openOrCloseCamera(paramsBean);
                    if (retInfo.getMark().equals("0")) {
                        int live_cou_his_id = Integer.valueOf(paramsBean.getParams().get("live_cou_his_id").toString());
                        List<TdNtMember> tdNtMembers = liveService.findTdNtMemberByLive(live_cou_his_id);
                        for (int i = 0; i < tdNtMembers.size(); i++) {
                            if (cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client") != null) {
                                cilentChannelMap.get(tdNtMembers.get(i).getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                            }

                        }
                        TdNtTeacherResult tdNtTeacherResult = liveService.findTdNtTeacher(live_cou_his_id);
                        cilentChannelMap.get(tdNtTeacherResult.getToken() + "client").writeAndFlush(BeanToJson.RetInfoToJson(retInfo));
                    }

                    break;
                }

            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }


    @Override
    public String toString() {
        return super.toString() + "{" +
                "id=" + id +
                ", channel=" + channel.toString() +
                '}';
    }
}